﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceModel.Activation;
using System.Text;
using LotteryWCF.Behavior;
using LotteryWCF.Commom;
using LotteryWCF.Constract;
namespace LotteryWCF
{
	// 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“Service1”。
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class LotteryService : ILotteryService
	{
		[MOperationBehavior]
		public User GetUserInfo(string userid)
		{
			string sql = String.Format("select * from UserInfo where userid='{0}'", userid);
			return SqlHelper.getInstance.ExcuteForList<User>(sql).FirstOrDefault();
		}

		[MOperationBehavior]
		public Capital GetCapitalInfo(string userid)
		{
			string sql = String.Format("select * from CapitalInfo where userid='{0}'", userid);
			List<Capital> list = SqlHelper.getInstance.ExcuteForList<Capital>(sql);
			return list.FirstOrDefault();
		}

		[MOperationBehavior]
		public User GetAdmin()
		{
			string sqlGetAdmin = "select * from UserInfo where ParentUID is null";
			User userAdmin = SqlHelper.getInstance.ExcuteForList<User>(sqlGetAdmin).FirstOrDefault();
			return userAdmin;
		}

		[MOperationBehavior]
		public int UpdateCapitalInfo(Capital cp)
		{
			string sql = string.Format("update CapitalInfo set EnableScores={0},DisableScores={1},GameScores={2} where UserID='{3}'",
									cp.EnableScores, cp.DisableScores, cp.GameScores, cp.UserId);
			return SqlHelper.getInstance.ExcuteNonQuery(sql);
		}

		[MOperationBehavior]
		public bool ValidateLogin(string userid, string userpwd)
		{
			string sql = String.Format("select * from UserInfo where userid='{0}' and userpwd='{1}' and IsActive=1 and RoleID!=1", userid, userpwd);
			bool result = SqlHelper.getInstance.ExcuteExist(sql);
			if (result)
			{
				sql = string.Format("update UserInfo set IsOnline=1,LastLoginTime='{0}' where userid='{1}' ",
				   DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), userid);
				SqlHelper.getInstance.ExcuteNonQuery(sql);
				Log log = new Log()
				{
					BfOrBehind = 0,
					LogContent = "登录",
					LogTime = DateTime.Now,
					LogTitle = "登录",
					UserID = userid,
					LogIp = Common.GetClientIp()
				};
				WriteLoginLog(log);
			}
			return result;
		}

		[MOperationBehavior]
		public void LoginOut(string userid)
		{
			string sql = string.Format("update UserInfo set IsOnline=0 where userid='{0}' ", userid);
			SqlHelper.getInstance.ExcuteNonQuery(sql);
		}

		[MOperationBehavior]
		public List<BankInfo> GetBankInfo(string userid)
		{
			string sql = String.Format("select BankType,UserName,CardNo,BankPwd from BankInfo where UserID='{0}'", userid);
			List<BankInfo> list = SqlHelper.getInstance.ExcuteForList<BankInfo>(sql);
			return list;
		}

		[MOperationBehavior]
		public BonusInfo GetBonusInfo(string userid, int playTypeId, int lotteryTypeId, int playtyperadioId)
		{
			string sql = String.Format("select * from BonusInfo where userid='{0}' and playtypeid={1} and lotterytypeid={2} and PlayTypeRadioID={3}",
				userid, playTypeId, lotteryTypeId, playtyperadioId);
			List<BonusInfo> list = SqlHelper.getInstance.ExcuteForList<BonusInfo>(sql);
			return list.FirstOrDefault();
		}

		[MOperationBehavior]
		public void ModifyPassword(string userid, string userpwd)
		{
			string sql = String.Format("update UserInfo set userpwd='{0}' where userid='{1}'", userpwd, userid);
			SqlHelper.getInstance.ExcuteNonQuery(sql);
		}

		[MOperationBehavior]
		public bool ValidateBankPassword(string userid, string bankPwd)
		{
			string sql = "select * from BankInfo where UserID=@UserID and BankPwd=@BankPwd";
			Dictionary<string, object> dic = new Dictionary<string, object>();
			dic.Add("UserID", userid);
			dic.Add("BankPwd", bankPwd);
			return SqlHelper.getInstance.ExcuteExistForParaMeters(sql, dic);
		}

		User GetUpperUser(string userid)
		{
			string sql = "select * from UserInfo where UserID='" + userid + "'";
			return SqlHelper.getInstance.ExcuteForList<User>(sql).FirstOrDefault();
		}
		[MOperationBehavior]
		public int ApplyMoneyOut(string userid, double money, double oneDayMoney, int oneDayTimes, string BankType)
		{
			string sql = string.Format("select * from MoneyOutInfo where UserID='{0}' and Status!=2 and ApplyTime between '{1}' and '{2}'",
						   userid, DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"),
						   DateTime.Now.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss"));
			if (SqlHelper.getInstance.ExcuteForDataTable(sql).Rows.Count >= oneDayTimes)
				return -1;
			sql = string.Format("select sum(Amount) as Amount from MoneyOutInfo where UserID='{0}' and Status!=2 and ApplyTime between '{1}' and '{2}'",
						   userid, DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"),
						   DateTime.Now.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss"));
			object obj = SqlHelper.getInstance.ExcuteScalar(sql);
			if (obj != DBNull.Value && obj != null && (Convert.ToDouble(obj) + money) > oneDayMoney)
				return -2;
			Capital cp = GetCapitalInfo(userid);
			if (cp == null)
				return -3;
			string sql_1 = String.Format(@"insert into MoneyOutInfo(UserID,Amount,ApplyTime,Status,BankType) values('{0}',{1},'{2}',{3},'{4}');
                                           select @@Identity;",
							userid, money, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), 0, BankType);
			int recordId = Convert.ToInt32(SqlHelper.getInstance.ExcuteScalar(sql_1));
			string sql_2 = String.Format("update CapitalInfo set EnableScores={0},DisableScores={1} where UserID='{2}'",
							cp.EnableScores - money, cp.DisableScores + money, userid);
			if (SqlHelper.getInstance.ExcuteNonQuery(sql_2) == 0)
			{
				sql = "delete from MoneyOutInfo where RecordID=" + recordId.ToString();
				SqlHelper.getInstance.ExcuteNonQuery(sql);
				return -3;
			}
			else
			{
				sql = "select count(*) from MoneyOutInfo where RecordID<" + recordId.ToString() + " and Status=0";
				return Convert.ToInt32(SqlHelper.getInstance.ExcuteScalar(sql));
			}
		}

		[MOperationBehavior]
		public List<CarrierBankInfo> GetCarrierBankInfo()
		{
			string sql = String.Format("select * from CarrierBankInfo where IsEnable=0");
			List<CarrierBankInfo> list = SqlHelper.getInstance.ExcuteForList<CarrierBankInfo>(sql);
			return list;
			//Random r = new Random();
			//int index = r.Next(0, list.Count - 1);
			//return list[index];
		}

		[MOperationBehavior]
		public void ModifyBankPwd(string userid, string userpwd)
		{
			string sql = String.Format("update BankInfo set BankPwd='{0}' where UserID='{1}'", userpwd, userid);
			SqlHelper.getInstance.ExcuteNonQuery(sql);
		}
		//===========下注用=================Begin

		[MOperationBehavior]
		public Dictionary<string, double> GetRemaindCount(string issue, int playtype, int playtyperadio, string nums)
		{
			if (nums.Length == 0)
				return new Dictionary<string, double>();
			string nums_para = string.Empty;
			for (int i = 0; i < nums.Length; i++)
			{
				if (i != nums.Length - 1)
					nums_para += ("'" + nums.Substring(i, 1) + "',");
				else
					nums_para += ("'" + nums.Substring(i, 1) + "'");
			}
			string sql = string.Format(@"select RemainderCount,Num from OddsInfo 
                                     where IssueNo='{0}' and PlayTypeID={1} and PlayTypeRadioID={2} and Num in({3})",
										 issue, playtype, playtyperadio, nums_para);
			DataTable dt = SqlHelper.getInstance.ExcuteForDataTable(sql);
			Dictionary<string, double> result = new Dictionary<string, double>();
			foreach (DataRow dr in dt.Rows)
			{
				result.Add(dr["Num"].ToString(), Convert.ToDouble(dr["RemainderCount"].ToString()));
			}
			return result;
		}

		[MOperationBehavior]
		public List<User> GetAllParentUser(string userId)
		{
			User user = GetUserInfo(userId);
			if (user == null)
				return new List<User>();
			string[] paraentIds = user.FullPath.ToString().Split('/');
			StringBuilder ids = new StringBuilder();
			for (int i = 0; i < paraentIds.Length - 1; i++)
			{
				ids.Append(paraentIds[i] + ",");
			}
			if (ids.Length == 0)
				return new List<User>();
			string sql = string.Format("select * from userinfo where (ID in({0}) and ParentUID is not Null)  order by ID desc", ids.ToString().Substring(0, ids.Length - 1));
			return SqlHelper.getInstance.ExcuteForList<User>(sql);
		}

		[MOperationBehavior]
		public List<Capital> GetAllParentCapital(List<User> list)
		{
			if (list.Count == 0)
				return new List<Capital>();
			StringBuilder sb = new StringBuilder();
			foreach (User u in list)
			{
				sb.Append("'" + u.UserId + "'");
				if (u != list.Last())
					sb.Append(",");
			}
			string sql = string.Format("select * from CapitalInfo where UserID in ({0})", sb.ToString());
			return SqlHelper.getInstance.ExcuteForList<Capital>(sql);
		}

		public int InsertBetRecord(BetRecord record)
		{
			record.BetTime = DateTime.Now;
			int recordId = SqlHelper.getInstance.ExcuteInsertReturnAutoID<BetRecord>(record, "BetRecord", "RecordID,LotteryName,PlayTypeName,UpdateTime");
			record.RecordID = recordId;
			if (!UpdateBetRecord_Pfl_Cap(record))
			{
				SqlHelper.getInstance.ExcuteNonQuery(string.Format("delete from BetRecord where RecordID={0}", recordId));
				return 0;
			}
			return recordId;
		}

		public int InsertBetRecordList(List<BetRecord> list)
		{
			foreach (BetRecord record in list)
			{
				record.BetTime = DateTime.Now;
				int recordId = SqlHelper.getInstance.ExcuteInsertReturnAutoID<BetRecord>(record, "BetRecord", "RecordID,LotteryName,PlayTypeName,UpdateTime");

				if ((LotteryTypeAll)record.LotteryTypeID == LotteryTypeAll.N3D
					|| (LotteryTypeAll)record.LotteryTypeID == LotteryTypeAll.NSSC
					|| (LotteryTypeAll)record.LotteryTypeID == LotteryTypeAll.NSSQ)
				{
					string sql = @"update OddsInfo set RemainderCount={0} 
                                where IssueNo='{1}' and PlayTypeID={2} and PlayTypeRadioID={3} and Num ='{4}'";
					object obj = SqlHelper.getInstance.ExcuteScalar(string.Format(@"select RemainderCount from OddsInfo 
                                     where IssueNo='{0}' and PlayTypeID={1} and PlayTypeRadioID={2} and Num ='{3}'",
										 record.IssueNo, record.PlayTypeID, record.PlayTypeRadioID, record.BetNums));
					if (obj != null)
					{
						double remaindCount = Convert.ToDouble(obj);
						sql = string.Format(sql, remaindCount - record.BetMultiple,
									record.IssueNo, record.PlayTypeID, record.PlayTypeRadioID, record.BetNums);
						SqlHelper.getInstance.ExcuteNonQuery(sql);
					}
				}
				record.RecordID = recordId;
				if (!UpdateBetRecord_Pfl_Cap(record))
				{
					SqlHelper.getInstance.ExcuteNonQuery(string.Format("delete from BetRecord where RecordID={0}", recordId));
					return 0;
				}
			}
			return 1;
		}


		public bool UpdateBetRecord_Pfl_Cap(BetRecord record)
		{
			List<ProfitLossInfo> list_pfloss = new List<ProfitLossInfo>();
			User user = GetUserInfo(record.UserID);
			//投注
			ProfitLossInfo pflInfo = new ProfitLossInfo();
			List<LotteryTypeInfo> lottery = GetLotteryType();
			LotteryTypeInfo currentLottery = (from l in lottery where l.LotteryTypeID == record.LotteryTypeID select l).FirstOrDefault();
			pflInfo.Memo = currentLottery.LotteryName + "[" + record.IssueNo + "]-" + record.PlayTypeDirection;
			pflInfo.ProfitLossTime = record.BetTime;
			pflInfo.ProfitLossType = "投注";
			pflInfo.RecordID = record.RecordID;
			pflInfo.UserID = record.UserID;
			if (record.Direction == 1)
				pflInfo.CurrentEnableScores = GetCapitalInfo(record.UserID).EnableScores - record.BetMoney + Math.Round(user.Bonus / 100 * record.BetMoney, 2);
			else
				pflInfo.CurrentEnableScores = GetCapitalInfo(record.UserID).EnableScores - record.BetMoney + Math.Round(record.BonusPct / 100 * record.BetMoney, 2);
			pflInfo.ProfitLossMoney = -record.BetMoney;

			list_pfloss.Add(pflInfo);
			//SqlHelper.getInstance.ExcuteInsert<ProfitLossInfo>(pflInfo, "ProfitLoss", "");
			//返点上级

			List<User> AllParentUser = GetAllParentUser(record.UserID);
			List<Capital> AllParentCapital = GetAllParentCapital(AllParentUser);
			foreach (User _user in AllParentUser)
			{
				if (_user.UserId == record.UserID)
					continue;
				Capital _cp = AllParentCapital.Where(c => c.UserId == _user.UserId).FirstOrDefault();
				_cp.EnableScores += Math.Round((_user.Bonus - user.Bonus) / 100 * record.BetMoney, 2);
				_cp.GameScores += Math.Round((_user.Bonus - user.Bonus) / 100 * record.BetMoney, 2);

				//返点
				pflInfo = new ProfitLossInfo();
				pflInfo.Memo = currentLottery.LotteryName + "[" + record.IssueNo + "]-" + record.PlayTypeDirection;
				pflInfo.ProfitLossTime = record.BetTime;
				pflInfo.ProfitLossType = "返点";
				pflInfo.RecordID = record.RecordID;
				pflInfo.UserID = _user.UserId;
				pflInfo.CurrentEnableScores = _cp.EnableScores;
				pflInfo.ProfitLossMoney = Math.Round((_user.Bonus - user.Bonus) / 100 * record.BetMoney, 2);
				list_pfloss.Add(pflInfo);
				user = _user;
			}
			//返点自己并冻结投注资金
			Capital cp = GetCapitalInfo(record.UserID);
			user = GetUserInfo(record.UserID);
			if (record.Direction == 1)//逆向
			{
				cp.EnableScores = Math.Round(cp.EnableScores - Math.Round(record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1), 2)
					+ Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
				cp.DisableScores = Math.Round(cp.DisableScores + Math.Round(record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1), 2)
					- Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
			}
			else
			{
				cp.EnableScores = Math.Round(cp.EnableScores - record.BetMoney + Math.Round((record.BonusPct / 100) * record.BetMoney, 2), 2);
				cp.DisableScores = Math.Round(cp.DisableScores + record.BetMoney - Math.Round((record.BonusPct / 100) * record.BetMoney, 2), 2);
			}
			cp.GameScores = Math.Round(cp.GameScores, 2);
			AllParentCapital.Add(cp);
			if (cp.EnableScores < 0)
				return false;
			//pflInfo = new ProfitLossInfo();
			//pflInfo.Memo = currentLottery.LotteryName + "[" + record.IssueNo + "]-" + record.PlayTypeDirection;
			//pflInfo.ProfitLossTime = record.BetTime;
			//pflInfo.ProfitLossType = "返点";
			//pflInfo.RecordID = record.RecordID;
			//pflInfo.UserID = record.UserID;
			//pflInfo.CurrentEnableScores = cp.EnableScores;
			//pflInfo.ProfitLossMoney = Math.Round(record.BonusPct / 100 * record.BetMoney, 2);
			//list_pfloss.Add(pflInfo);
			//UpdateCapitalInfo(cp);
			#region
			//============更新admin账户资金===============
			User userAdmin = GetAdmin();
			Capital cpAdmin = GetCapitalInfo(userAdmin.UserId);

			List<ProfitLossInfo> listAdmin_Pfl = new List<ProfitLossInfo>();
			//收入:投注
			cpAdmin.GameScores = cpAdmin.GameScores + record.BetMoney - Math.Round(record.BonusPct / 100 * record.BetMoney, 2);//投注,admin收入
			ProfitLossInfo betAdmin = new ProfitLossInfo();
			betAdmin.CurrentEnableScores = cpAdmin.GameScores;
			betAdmin.Memo = record.UserID + "投注,下注金额:" + record.BetMoney.ToString() + ",玩法:" + record.PlayTypeDirection;
			betAdmin.ProfitLossType = "投注";
			betAdmin.ProfitLossMoney = Math.Abs(record.BetMoney) - Math.Round(record.BonusPct / 100 * record.BetMoney, 2);
			betAdmin.ProfitLossTime = DateTime.Now;
			betAdmin.RecordID = record.RecordID;
			betAdmin.UserID = userAdmin.UserId;
			listAdmin_Pfl.Add(betAdmin);
			//支出:返点
			ProfitLossInfo fdAdmin = new ProfitLossInfo();
			cpAdmin.GameScores = cpAdmin.GameScores - list_pfloss.Where(p => p.ProfitLossType == "返点").Sum(p => p.ProfitLossMoney);
			fdAdmin.CurrentEnableScores = cpAdmin.GameScores;
			fdAdmin.Memo = record.UserID + "以及其上级返点,下注金额:" + record.BetMoney.ToString() + ",玩法:" + record.PlayTypeDirection;
			fdAdmin.ProfitLossType = "返点";
			fdAdmin.ProfitLossMoney = -list_pfloss.Where(p => p.ProfitLossType == "返点").Sum(p => p.ProfitLossMoney);
			fdAdmin.ProfitLossTime = DateTime.Now;
			fdAdmin.RecordID = record.RecordID;
			fdAdmin.UserID = userAdmin.UserId;
			listAdmin_Pfl.Add(fdAdmin);
			//===================================
			#endregion

			list_pfloss.AddRange(listAdmin_Pfl);
			AllParentCapital.Add(cpAdmin);

			//事务批量更新
			List<SQLTranCationParaMeters> paras = new List<SQLTranCationParaMeters>()
            {
                new SQLTranCationParaMeters()
                {
                    SqlText="update CapitalInfo set GameScores=@GameScores,EnableScores=@EnableScores,DisableScores=@DisableScores where UserID=@UserId",
                    type=typeof(Capital),
                    ParameterName=new string[]{"GameScores","EnableScores","UserId","DisableScores"},
                    Data=ConvertHelper.ToListDictionary<Capital>(AllParentCapital)
                },
                new SQLTranCationParaMeters()
                {
                    SqlText =@"Insert into ProfitLoss values(@UserID,@ProfitLossTime,@Memo,@ProfitLossType, 
                             @CurrentEnableScores,@RecordID,@ProfitLossMoney)",
                    type=typeof(ProfitLossInfo),
                    ParameterName=new string[] { "UserID", "ProfitLossTime","Memo","ProfitLossType", 
                                                "CurrentEnableScores", "RecordID", "ProfitLossMoney"},
                    Data=ConvertHelper.ToListDictionary<ProfitLossInfo>(list_pfloss)
                }
            };
			return SqlHelper.getInstance.ExcuteInsertTrancation(paras);
		}
		//===========下注用=================End

		[MOperationBehavior]
		public int InsertUser(User user)
		{
			return SqlHelper.getInstance.ExcuteInsert<User>(user, "UserInfo");
		}

		[MOperationBehavior]
		public bool UpdateBonus(BonusInfo bonus)
		{
			string sql = String.Format("delete from BonusInfo where UserID='{0}' and PlayTypeID={1} and LotteryTypeID={2} and PlayTypeRadioID={3}",
				bonus.UserID, bonus.PlayTypeID, bonus.LotteryTypeID, bonus.PlayTypeRadioID);
			SqlHelper.getInstance.ExcuteNonQuery(sql);
			if (SqlHelper.getInstance.ExcuteInsert<BonusInfo>(bonus, "BonusInfo") > 0)
				return true;
			else
				return false;
		}

		[MOperationBehavior]
		public List<LotteryTypeInfo> GetLotteryType()
		{
			string sql = "select * from LotteryTypeInfo where IsEnable=0";
			return SqlHelper.getInstance.ExcuteForList<LotteryTypeInfo>(sql);
		}

		[MOperationBehavior]
		public bool SetBankInfo(string userid, string BankType, string accountName, string BankPwd, string cardNo)
		{
			string sql = string.Format("select UserID from BankInfo where CardNo='{0}'", cardNo);
			if (SqlHelper.getInstance.ExcuteExist(sql))
			{
				return false;
			}
			else
			{
				sql = String.Format("insert into BankInfo(UserID,BankType,UserName,BankPwd,CardNo) values('{0}','{1}','{2}','{3}','{4}')", userid, BankType, accountName, BankPwd, cardNo);
				SqlHelper.getInstance.ExcuteNonQuery(sql);
				return true;
			}
		}

		[MOperationBehavior]
		public List<PlayTypeInfo> GetPlayType(int LotteryId)
		{
			string sql = "select * from PlayTypeInfo a left join LotteryTypeInfo b on a.LotteryTypeID=b.LotteryTypeID "

			+ "where a.isEnable=0 and b.isEnable=0 and a.LotteryTypeID=" + LotteryId;
			return SqlHelper.getInstance.ExcuteForList<PlayTypeInfo>(sql);
		}

		[MOperationBehavior]
		public List<PlayTypeRadioInfo> GetPlayTypeRadio()
		{
			string sql = "select c.* from PlayTypeRadio c left join PlayTypeInfo a on c.PlayTypeID=a.PlayTypeID "
		   + "left join LotteryTypeInfo b on a.LotteryTypeID=b.LotteryTypeID "
		   + "where a.isEnable=0 and b.isEnable=0 and c.isEnable=0";
			return SqlHelper.getInstance.ExcuteForList<PlayTypeRadioInfo>(sql);
		}

		[MOperationBehavior]
		public List<PlayTypeNumInfo> GetPlayTypeNum()
		{
			string sql = "select * from PlayTypeNum c left join PlayTypeInfo a on c.PlayTypeID=a.PlayTypeID "
		   + "left join LotteryTypeInfo b on a.LotteryTypeID=b.LotteryTypeID "
		   + "where a.isEnable=0 and b.isEnable=0 and c.isEnable=0";
			return SqlHelper.getInstance.ExcuteForList<PlayTypeNumInfo>(sql);
		}

		[MOperationBehavior]
		public List<PlayTypeInfo> GetPlayTypeInfo()
		{
			string sql = "select a.* from PlayTypeInfo a left join LotteryTypeInfo b on a.LotteryTypeID=b.LotteryTypeID "
			+ "where a.IsEnable=0 and b.IsEnable=0";
			return SqlHelper.getInstance.ExcuteForList<PlayTypeInfo>(sql);
		}

		[MOperationBehavior]
		public List<Dictionary<string, string>> GetOdds(int playTypeId, int PlayTypeRadioID, string IssueNo)
		{
			string sql = Common.GetOddsSql(playTypeId, IssueNo, PlayTypeRadioID);
			if (sql == string.Empty)
				return new List<Dictionary<string, string>>();
			List<Dictionary<string, string>> List = SqlHelper.getInstance.ExcuteForListDic(sql);
			sql = Common.GetRemainSql(playTypeId, IssueNo, PlayTypeRadioID);
			if (sql == string.Empty)
				return new List<Dictionary<string, string>>();
			List.AddRange(SqlHelper.getInstance.ExcuteForListDic(sql));
			return List;
		}

		[MOperationBehavior]
		public bool AddLowerInfo(LowerInfo info)
		{
			string sql = "select * from UserInfo where UserID='" + info.UserID + "'";
			if (SqlHelper.getInstance.ExcuteExist(sql))
				return false;
			string[] sqls = new string[2];
			string sql_1 = String.Format(@"insert into UserInfo(UserID,UserPwd,ParentUID,RegTime,IsOnline,IsActive,Bonus,FullPath,RoleID)
                              values('{0}','{1}',{2},'{3}',{4},{5},{6},'{7}',{8})", info.UserID, info.UserPwd, info.ParentUID, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), 0,
							1, info.Bonus, info.FullPath, info.RoleID);
			sqls[0] = sql_1;
			string sql_2 = "insert into CapitalInfo(userID,GameScores,EnableScores,DisableScores) values('" + info.UserID + "',0,0,0)";
			sqls[1] = sql_2;
			bool returnValue = SqlHelper.getInstance.ExcuteTrancationForSQL(sqls);
			User user = SqlHelper.getInstance.ExcuteForList<User>(sql).FirstOrDefault();
			if (user != null)
			{
				sql = "update CapitalInfo set ID=" + user.ID + " where UserID='" + info.UserID + "'";
				SqlHelper.getInstance.ExcuteNonQuery(sql);
			}
			return returnValue;
		}

		[MOperationBehavior]
		public bool EditLowerInfo(LowerInfo info)
		{
			string sql = String.Format(@"update UserInfo set Bonus={0} where UserID='{1}'", info.Bonus, info.UserID);
			if (SqlHelper.getInstance.ExcuteNonQuery(sql) > 0)
				return true;
			else
				return false;
		}

		[MOperationBehavior]
		public List<LowerListData> GetLowerListData(Int64 ID)
		{
			string sql = @"select t1.ID,t1.UserID, LastLoginTime,t1.IsOnline,
                          case when t1.IsActive=1 then '激活' else '锁定' end as IsActive,t2.RoleName,t1.Bonus,t3.GameScores,
                          t3.EnableScores,t3.DisableScores from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                          left join CapitalInfo t3 on t1.UserID=t3.UserID where t1.ID='" + ID + "' or t1.ParentUID='" + ID + "'";
			List<LowerListData> list = SqlHelper.getInstance.ExcuteForList<LowerListData>(sql);
			return list;
		}

		[MOperationBehavior]
		public List<LowerListData> GetLowerListDataByUID(string UID, Int64 ID)
		{
			string sql = @"select t1.ID,t1.UserID, LastLoginTime,t1.IsOnline,
                          case when t1.IsActive=1 then '激活' else '锁定' end as IsActive,t2.RoleName,t1.Bonus,t3.GameScores,
                          t3.EnableScores,t3.DisableScores from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                          left join CapitalInfo t3 on t1.UserID=t3.UserID where t1.UserID='" + UID + "' and  t1.ParentUID=" + ID;
			List<LowerListData> list = SqlHelper.getInstance.ExcuteForList<LowerListData>(sql);
			return list;
		}

		[MOperationBehavior]
		public LotteryNumsInfo GetCurrenIssuNo(int lotteryId)
		{
			string sql = @"select * from LotteryNumsInfo 
            where (LotteryNums='' or LotteryNums is null)
            and LotteryTypeID=" + lotteryId + " order by LotteryDate desc";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql).FirstOrDefault();
		}

		[MOperationBehavior]
		public LotteryNumsInfo GetLastLotteryNum(int lotteryId)
		{
			string sql = @"select * from LotteryNumsInfo 
            where  IssueNo=(select max(IssueNo) from LotteryNumsInfo
            where  LotteryNums!='' and LotteryNums is not null  and LotteryTypeID=" + lotteryId + @") order by LotteryDate desc";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql).FirstOrDefault();
		}

		[MOperationBehavior]
		public List<LotteryNumsInfo> GetRecentlyLotteryNum(int lotteryId)
		{
			string sql = @"select top 5 * from LotteryNumsInfo 
            where  LotteryTypeID=" + lotteryId + @" and lotterynums!='' and lotterynums is not null 
            order by IssueNo desc ";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql);
		}

		[MOperationBehavior]
		public LotteryNumsInfo GetNewLotteryNum(int lotteryId, string issueNo)
		{
			string sql = @"select * from LotteryNumsInfo 
            where  LotteryTypeID=" + lotteryId + @" and IssueNo='" + issueNo + "'";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql).FirstOrDefault();
		}

		[MOperationBehavior]
		public List<BetRecord> GetBetRecord(string userid)
		{
			string sql = string.Format(@"select a.*,b.LotteryName from BetRecord a left join LotteryTypeInfo b 
            on a.LotteryTypeID=b.LotteryTypeID
            where userid='{0}' and ResultStatus=0 and BetTime between '{1}' and '{2}' order by RecordID desc"
				, userid, System.DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"),
				System.DateTime.Now.Date.AddDays(1).AddMilliseconds(-1).ToString("yyyy-MM-dd HH:mm:ss"));
			return SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
		}
		//=================采集用==================Begin

		[MOperationBehavior]
		public int InsertLotteryNums(LotteryNumsInfo info)
		{
			LotteryNumsInfo lottery = GetCurrenIssuNo(Convert.ToInt32(info.LotteryTypeID));
			if (lottery != null && lottery.IssueNo == info.IssueNo && (lottery.LotteryNums == null || lottery.LotteryNums.Trim() == ""))
			{
				return 0;
			}
			else
			{
				string sql = string.Format(@"insert into oddsInfo(PlayTypeID,PlayTypeRadioID,Num,NumOdds,RemainderCount,IssueNo)
                            select PlayTypeID,PlayTypeRadioID,Num,NumOdds,
                            Allcount, '{0}' as IssueNo from defaultoddsinfo 
                            where playTypeID in(select distinct PlayTypeID from PlayTypeInfo where LotteryTypeID in 
                            (select LotteryTypeID from LotteryTypeInfo where LotteryID={1}))",
							info.IssueNo, info.LotteryTypeID);
				if (SqlHelper.getInstance.ExcuteScalar("select IssueNo from oddsInfo where IssueNo='" + info.IssueNo + "'") == null)
					SqlHelper.getInstance.ExcuteNonQuery(sql);
				return SqlHelper.getInstance.ExcuteInsert<LotteryNumsInfo>(info, "LotteryNumsInfo", "LotteryNums,UpdateTime,UpdateUser,Size,Parity");
			}
		}

		[MOperationBehavior]
		public int UpdateLotteryNums(LotteryNumsInfo info)
		{
			LotteryNumsInfo lottery = SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(string.Format("select * from LotteryNumsInfo where IssueNo='{0}' and LotteryTypeID={1}", info.IssueNo, info.LotteryTypeID)).FirstOrDefault();
			if (lottery.LotteryNums == null || lottery.LotteryNums.Trim() == "")
			{

				string sql = string.Format("update LotteryNumsInfo set LotteryNums='{0}',UpdateTime='{1}',UpdateUser='{2}' where IssueNo='{3}' and LotteryTypeID={4}",
											info.LotteryNums, info.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
											info.UpdateUser, info.IssueNo, info.LotteryTypeID);
				return SqlHelper.getInstance.ExcuteNonQuery(sql);
			}
			else
			{
				return 0;
			}
		}
		//=================采集用=======================

		[MOperationBehavior]
		public int InsertProfitLoss(ProfitLossInfo info)
		{
			return SqlHelper.getInstance.ExcuteInsert<ProfitLossInfo>(info, "ProfitLossInfo");
		}
		//=================开奖用==================End

		[MOperationBehavior]
		public List<LotteryNumsInfo> getIsNotPJ(int type)
		{
			string sql = "select * from LotteryNumsInfo where LotteryTypeID=" + type +
				" and (isDistributed=0 or isDistributed=1) and LotteryNums!='' and LotteryNums is not null";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql);
		}

		[MOperationBehavior]
		public List<LotteryNumsInfo> updatePjStatus(int status, int type)
		{
			string sql = "update LotteryNumsInfo set isDistributed=" + status +
				" where  LotteryTypeID=" + type +
				" and isDistributed=0 and LotteryNums!='' and LotteryNums is not null";
			return SqlHelper.getInstance.ExcuteForList<LotteryNumsInfo>(sql);
		}

		[MOperationBehavior]
		public List<BetRecord> getOrders(string IssueNo, int type)
		{
			string sql = @"select * from BetRecord where IssueNo='" + IssueNo +
				"' and ResultStatus=0 and LotteryTypeID in(select LotteryTypeID from LotteryTypeInfo where LotteryID=" + type + ")";
			return SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
		}
		public List<BetRecord> getOrders2(string IssueNo, int type, string orderid)
		{
			string sql = @"select * from BetRecord where IssueNo='" + IssueNo +
				"' and RecordId=" + orderid + " and LotteryTypeID in(select LotteryTypeID from LotteryTypeInfo where LotteryID=" + type + ")";
			return SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
		}
		[MOperationBehavior]
		public int UpdateLotteryFlag(int Flag, Int64 LotteryId, string issueNo)
		{
			string sql = string.Format("update LotteryNumsInfo set isDistributed={0} where LotteryTypeID={1} and IssueNo='{2}'", Flag, LotteryId, issueNo);
			return SqlHelper.getInstance.ExcuteNonQuery(sql);
		}

		public int UpdateOrdersWinInfo(BetRecord record)
		{
			string sql = string.Format(@"update BetRecord  set ResultStatus=1,WinCount={0},
                            WinMoney={1},IsWin={2},UpdateTime='{3}' where RecordID={4}",
							record.WinCount, record.WinMoney, record.IsWin,
							record.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"), record.RecordID);
			return SqlHelper.getInstance.ExcuteNonQuery(sql);
		}

		[MOperationBehavior]
		public bool UpdateOrdersWinInfo(List<BetRecord> betrecord_list)
		{
			List<ProfitLossInfo> pfl_list = new List<ProfitLossInfo>();
			List<Capital> capital_list = new List<Capital>();
			//admin账户========
			User userAdmin = GetAdmin();
			Capital cpAdmin = GetCapitalInfo(userAdmin.UserId);
			//=================
			foreach (BetRecord record in betrecord_list)
			{
				Capital cp = new Capital();
				if (capital_list.Exists(p => p.UserId == record.UserID))
				{
					cp = capital_list.Find(p => p.UserId == record.UserID);
					capital_list.Remove(cp);
				}
				else
					cp = GetCapitalInfo(record.UserID);
				if (cp == null)
					continue;
				if (record.Direction == 0)
				{
					cp.GameScores = Math.Round(cp.GameScores + record.WinMoney - record.BetMoney + Math.Round(record.BonusPct / 100 * record.BetMoney, 2), 2);
					cp.EnableScores = Math.Round(cp.EnableScores + record.WinMoney, 2);
					cp.DisableScores = Math.Round(cp.DisableScores - (record.BetMoney - Math.Round(record.BonusPct / 100 * record.BetMoney, 2)), 2);
				}
				else
				{
					User user = GetUserInfo(record.UserID);
					if (record.IsWin == 1)
					{
						double disabledS = record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1);
						cp.GameScores = Math.Round(cp.GameScores + record.BetMoney + Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
						cp.EnableScores = Math.Round(cp.EnableScores + record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1) + record.BetMoney, 2);
						cp.DisableScores = Math.Round(cp.DisableScores - record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1)
							+ Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
					}
					else
					{
						cp.GameScores = Math.Round(cp.GameScores - record.BetMoney + Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
						cp.EnableScores = cp.EnableScores + record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1) - record.BetMoney;
						cp.DisableScores = Math.Round(cp.DisableScores - record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1)
							+ Math.Round(record.BetMoney * user.Bonus / 100, 2), 2);
					}
				}
				capital_list.Add(cp);
				//admin
				if (record.Direction == 0)
					cpAdmin.GameScores = Math.Round(cpAdmin.GameScores - record.WinMoney, 2);
				else if (record.Direction == 1 && record.IsWin == 1)
					cpAdmin.GameScores = Math.Round(cpAdmin.GameScores - record.BetMoney * 2, 2);
				else
					cpAdmin.GameScores = Math.Round(cpAdmin.GameScores + record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1) - record.BetMoney, 2);
				pfl_list.Add(new ProfitLossInfo()
				{
					RecordID = record.RecordID,
					ProfitLossMoney = record.Direction == 0 ? Math.Round(record.WinMoney - record.BetMoney + Math.Round(record.BonusPct / 100 * record.BetMoney, 2), 2) :
					(record.IsWin == 1 ? Math.Round(record.WinMoney - record.BetMoney + Math.Round(record.BonusPct / 100 * record.BetMoney, 2), 2) : (-record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1))),
					ProfitLossTime = DateTime.Now,
					UserID = record.UserID,
					Memo = record.PlayTypeDirection,
					ProfitLossType = "盈亏",
					CurrentEnableScores = cp.EnableScores
				});
				//admin
				pfl_list.Add(new ProfitLossInfo()
				{
					RecordID = record.RecordID,
					ProfitLossMoney = record.Direction == 0 ? Math.Round(-record.WinMoney, 2) :
					(record.IsWin == 1 ? Math.Round(-record.WinMoney, 2) : (record.BetMoney * (Convert.ToDouble(record.OddBonus) - 1) - record.BetMoney)),
					ProfitLossTime = DateTime.Now,
					UserID = userAdmin.UserId,
					Memo = record.UserID + "中奖,下注金额:" + record.BetMoney.ToString() + ",中奖金额:" + record.WinMoney.ToString() + ",玩法:" + record.PlayTypeDirection,
					ProfitLossType = "盈亏",
					CurrentEnableScores = cpAdmin.GameScores
				});
			}
			//admin
			capital_list.Add(cpAdmin);
			List<SQLTranCationParaMeters> tran_list = new List<SQLTranCationParaMeters>();
			SQLTranCationParaMeters para = new SQLTranCationParaMeters();
			para.SqlText = @"update BetRecord  set ResultStatus=1,WinCount=@WinCount,
                            WinMoney=@WinMoney,IsWin=@IsWin,UpdateTime=@UpdateTime where RecordID=@RecordID";
			para.ParameterName = new string[] { "WinCount", "WinMoney", "IsWin", "UpdateTime", "RecordID" };
			para.Data = ConvertHelper.ToListDictionary<BetRecord>(betrecord_list);
			para.type = typeof(BetRecord);
			tran_list.Add(para);

			para = new SQLTranCationParaMeters();
			para.SqlText = @"Insert into ProfitLoss values(@UserID,@ProfitLossTime,@Memo,@ProfitLossType,
                             @CurrentEnableScores,@RecordID,@ProfitLossMoney)";
			para.ParameterName = new string[] { "UserID", "ProfitLossTime","Memo","ProfitLossType", 
                                                "CurrentEnableScores", "RecordID", "ProfitLossMoney"};
			para.Data = ConvertHelper.ToListDictionary<ProfitLossInfo>(pfl_list);
			para.type = typeof(ProfitLossInfo);
			tran_list.Add(para);

			para = new SQLTranCationParaMeters();
			para.SqlText = @"update CapitalInfo set GameScores=@GameScores,EnableScores=@EnableScores,DisableScores=@DisableScores
                            where UserID=@UserID";
			para.ParameterName = new string[] { "GameScores", "EnableScores", "DisableScores", "UserId" };
			para.Data = ConvertHelper.ToListDictionary<Capital>(capital_list);
			para.type = typeof(Capital);
			tran_list.Add(para);
			return SqlHelper.getInstance.ExcuteInsertTrancation(tran_list);
		}
		//=================开奖用==================End

		public DateTime GetServerCurrentTime()
		{
			return System.DateTime.Now;
		}

		[MOperationBehavior]
		public List<ProfitLossInfo> GetPfLoss_CZandTX(string userId)
		{
			string sql = string.Format(@"select * from ProfitLoss 
                        where UserID='{2}' and ProfitLossTime between '{0}' and '{1}' 
                        and (ProfitLossType='提现' or ProfitLossType='充值') ",
					   System.DateTime.Now.AddSeconds(-40).ToString("yyyy-MM-dd HH:mm:ss"), System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
					   userId);
			return SqlHelper.getInstance.ExcuteForList<ProfitLossInfo>(sql);
		}

		[MOperationBehavior]
		public List<ProfitLossInfo> GetPfLoss_TX_Pct(string userId)
		{
			string sql = string.Format(@"select * from ProfitLoss 
                        where UserID='{2}' and ProfitLossTime between '{0}' and '{1}' 
                        and (ProfitLossType='提现返点') ",
					   System.DateTime.Now.AddSeconds(-40).ToString("yyyy-MM-dd HH:mm:ss"), System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
					   userId);
			return SqlHelper.getInstance.ExcuteForList<ProfitLossInfo>(sql);
		}

		[MOperationBehavior]
		public List<PfLossMsg> GetPfLoss_YK(string userId, string IssueNo)
		{
			string sql = string.Format(@"select a.UserID,ProfitLossType,b.IssueNo,sum(ProfitLossMoney) as ProfitLossMoney,
                        max(ProfitLossTime) as ProfitLossTime,c.LotteryName,count(*) as RecordCount 
                        from ProfitLoss a left join BetRecord b on a.RecordID=b.RecordID left join LotteryTypeInfo c
                        on b.LotteryTypeID=c.LotteryTypeID
                        where a.UserID='{0}' and b.IssueNo='{1}' and ProfitLossType='盈亏'
                        group by a.UserID,ProfitLossType,b.IssueNo,LotteryName", userId, IssueNo);
			return SqlHelper.getInstance.ExcuteForList<PfLossMsg>(sql);
		}

		[MOperationBehavior]
		public List<StatReport> GetStatReport(Int64 ID, DateTime start, DateTime end)
		{
			string sql = string.Format(@"select * from (
                                       select t1.UserID,t2.RoleName,t1.ID,sum(t3.BetMoney) as BetMoney,sum(t4.ProfitLossMoney) as WinMoney 
                                       from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                                       left join BetRecord t3 on t1.UserID=t3.UserID and t3.BetTime between '{1}' and '{2}'
                                       left join ProfitLoss t4 on t1.UserID=t4.UserID 
                                       and t4.recordid=t3.recordid and t4.ProfitLossType='盈亏' where 
                                       t1.ID={0}
                                       group by t1.UserID,t2.RoleName,t1.ID 
                                       union all 
                                       select t1.UserID,t2.RoleName,t1.ID,sum(t3.BetMoney) as BetMoney,sum(t4.ProfitLossMoney) as WinMoney 
                                       from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                                       left join BetRecord t3 on t1.UserID=t3.UserID and t3.BetTime between '{1}' and '{2}'
                                       left join ProfitLoss t4 on t1.UserID=t4.UserID 
                                       and t4.recordid=t3.recordid and t4.ProfitLossType='盈亏' where 
                                       t1.ParentUID={0} and BetMoney>0  
                                       group by t1.UserID,t2.RoleName,t1.ID 
                                       )ab order by ID ",
									ID, start.ToString("yyyy-MM-dd HH:mm:ss"), end.ToString("yyyy-MM-dd HH:mm:ss"));
			List<StatReport> list = SqlHelper.getInstance.ExcuteForList<StatReport>(sql);
			return list;
		}

		[MOperationBehavior]
		public List<ReportDetail> GetReportDetail(string UID, DateTime start, DateTime end)
		{
			string sql = string.Format(@"select t1.RecordID,t1.BetTime,t2.LotteryName,t1.PlayTypeDirection,t1.IssueNo,t1.Direction,
                                         t1.BetNums,t1.BetMoney,t1.IsWin,t3.ProfitLossMoney as WinMoney,t1.ResultStatus  
                                         from  BetRecord t1 left join LotteryTypeInfo 
                                         t2 on t1.LotteryTypeID=t2.LotteryTypeID left join 
                                         (select * from profitloss where UserID='{0}' and ProfitLossType='盈亏') t3 on t3.RecordID=t1.RecordID  
                                          where t1.UserID='{0}' and t1.BetTime between '{1}' and '{2}' order by t1.RecordID desc", UID, start.ToString("yyyy-MM-dd HH:mm:ss"), end.ToString("yyyy-MM-dd HH:mm:ss"));
			List<ReportDetail> list = SqlHelper.getInstance.ExcuteForList<ReportDetail>(sql);
			return list;
		}

		[MOperationBehavior]
		public List<ProfitReport> GetProfitReport(Int64 ID, DateTime start, DateTime end)
		{
			string sql = string.Format(@"select * from(
                                         select t1.ID as UID,t1.UserID,t2.RoleName,
                                         sum(case when t3.ProfitLossType ='充值' then t3.ProfitLossMoney else 0 end) as MoneyIn,
                                         sum(case when t3.ProfitLossType ='提现' then t3.ProfitLossMoney else 0 end) as MoneyOut,
                                         0-sum(case when t3.ProfitLossType ='投注' then t3.ProfitLossMoney else 0 end) as BetMoney,
                                         sum(case when t3.ProfitLossType ='返点' then t3.ProfitLossMoney else 0 end) as PctMoney,
                                         sum(case when t3.ProfitLossType ='提现返点' then t3.ProfitLossMoney else 0 end) as PctMoneyOut,
                                         sum(case when t3.ProfitLossType ='盈亏' then t3.ProfitLossMoney else 0 end) as ProfitLoss
                                         from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                                         left join ProfitLoss t3 on t1.UserID=t3.UserID and t3.ProfitLossTime between '{1}' and '{2}'
                                         where t1.ID={0} 
                                         group by t1.ID,t1.[UserID],t2.rolename) b 
                                         union all
                                         select * from(
                                         select t1.ID as UID,t1.UserID,t2.RoleName,
                                         sum(case when t3.ProfitLossType ='充值' then t3.ProfitLossMoney else 0 end) as MoneyIn,
                                         sum(case when t3.ProfitLossType ='提现' then t3.ProfitLossMoney else 0 end) as MoneyOut,
                                         0-sum(case when t3.ProfitLossType ='投注' then t3.ProfitLossMoney else 0 end) as BetMoney,
                                         sum(case when t3.ProfitLossType ='返点' then t3.ProfitLossMoney else 0 end) as PctMoney,
                                         sum(case when t3.ProfitLossType ='提现返点' then t3.ProfitLossMoney else 0 end) as PctMoneyOut,
                                         sum(case when t3.ProfitLossType ='盈亏' then t3.ProfitLossMoney else 0 end) as ProfitLoss
                                         from UserInfo t1 left join RoleInfo t2 on t1.RoleID=t2.RoleID
                                         left join ProfitLoss t3 on t1.UserID=t3.UserID and t3.ProfitLossTime between '{1}' and '{2}' 
                                         where t1.FullPath like '%{0}%' 
                                         group by t1.ID,t1.[UserID],t2.rolename)a where (MoneyOut>0 or BetMoney>0 or PctMoney>0 or ProfitLoss>0)",
										 ID, start.ToString("yyyy-MM-dd HH:mm:ss"), end.ToString("yyyy-MM-dd HH:mm:ss"));
			List<ProfitReport> list = SqlHelper.getInstance.ExcuteForList<ProfitReport>(sql);
			sql = string.Format(@"select sum(BetMoney) as BetMoney,a.UserID 
                                from BetRecord a left join UserInfo b on a.UserID=b.UserID 
                                where (b.ParentUID={0} or b.ID={0}) and a.BetTime between '{1}' and '{2}' group by a.UserID", ID, start, end);
			List<BetRecord> record = SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
			return list;
		}

		[MOperationBehavior]
		public List<ProfitDetail> GetProfitDetail(string UID, DateTime start, DateTime end)
		{
			string sql = string.Format(@"select RecordID,ProfitLossTime,Memo,ProfitLossType,ProfitLossMoney,CurrentEnableScores
                                        from  ProfitLoss where UserID='{0}' and ProfitLossTime between '{1}' and '{2}' and ProfitLossType!='投注'
                                        order by ProfitLossTime desc,RecordID desc"
									, UID, start.ToString("yyyy-MM-dd HH:mm:ss"), end.ToString("yyyy-MM-dd HH:mm:ss"));
			List<ProfitDetail> list = SqlHelper.getInstance.ExcuteForList<ProfitDetail>(sql);
			return list;
		}

		[MOperationBehavior]
		public OrderContent GetOrderContent(Int64 RecordID)
		{
			string sql = string.Format(@"select t1.BetNums,t1.UserID,t1.BetCount,t1.RecordID,t1.EachNumsMoney,t1.IssueNo,t1.BetMoney,t2.LotteryName,
                                         t1.PlayTypeDirection,t1.WinCount,t1.Direction,t1.OddBonus,t3.LotteryNums,t1.WinMoney,t1.BetTime,
                                         (t1.betmoney-(t1.WinMoney-t4.ProfitLossMoney)) as PctAndMoney,
                                         t1.IsWin,t4.ProfitLossMoney from BetRecord t1 left join LotteryTypeInfo t2 on t1.LotteryTypeID=t2.LotteryTypeID 
                                         left join LotteryNumsInfo t3 on t1.IssueNo=t3.IssueNo left join (select RecordID,
                                         sum(case when ProfitLossType='盈亏' then ProfitLossMoney else 0 end) 
                                         ProfitLossMoney from ProfitLoss where RecordID={0} and UserID not in(select UserID from UserInfo where ParentUID is null) 
                                         group by RecordID) t4 on t1.RecordID=t4.RecordID where t1.RecordID={0}", RecordID);
			OrderContent list = SqlHelper.getInstance.ExcuteForList<OrderContent>(sql).FirstOrDefault();
			return list;
		}

		[MOperationBehavior]
		public List<BetRecord> GetTopTenWinInfo(int lotteryId)
		{
			User userAdmin = GetAdmin();
			string sql = @"select top 10 *
            from BetRecord where LotteryTypeID={3} and WinMoney>0 
            and UpdateTime between '{0}' and '{1}' and UserID!='{2}'
            order by WinMoney desc ";
			sql = string.Format(sql, DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"),
				DateTime.Now.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss"), userAdmin.UserId, lotteryId);
			List<BetRecord> result = SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
			if (result.Count > 0)
				return result;
			sql = @"select top 10 *
            from BetRecord where LotteryTypeID={3} and WinMoney>0 
            and UpdateTime between '{0}' and '{1}' and UserID!='{2}'
            order by WinMoney desc ";
			sql = string.Format(sql, DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd HH:mm:ss"),
				DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), userAdmin.UserId, lotteryId);
			return SqlHelper.getInstance.ExcuteForList<BetRecord>(sql);
		}

		[MOperationBehavior]
		public List<string> GetNewsInfo()
		{
			string sql = "select * from news where IsEnable=0";
			List<News> list = SqlHelper.getInstance.ExcuteForList<News>(sql);
			List<string> result = new List<string>();
			foreach (News n in list)
			{
				string str = string.Empty;
				if (n.NewsType == 2)
					str = n.NewsType.ToString() + "|" + n.NewsContent + "|" + n.UrlAddress;
				else
					str = n.NewsType.ToString() + "|" + n.NewsContent;
				result.Add(str);
			}
			return result;
		}

		[MOperationBehavior]
		public Dictionary<string, string> GetOverAllCfg()
		{
			Dictionary<string, string> dic = new Dictionary<string, string>();
			string sql = "select * from OverallConfig";
			DataTable dtResult = SqlHelper.getInstance.ExcuteForDataTable(sql);
			foreach (DataRow dr in dtResult.Rows)
			{
				dic.Add(dr["key"].ToString(), dr["value"].ToString());
			}
			return dic;
		}

		[MOperationBehavior]
		public int GetMultipleByPlayTypeId(int PlayTypeId)
		{
			string sql = "select Multiple from PlayTypeInfo where PlayTypeID=" + PlayTypeId;
			object obj = SqlHelper.getInstance.ExcuteScalar(sql);
			if (obj == null)
				return 1;
			else
				return Convert.ToInt32(obj.ToString());
		}

		[MOperationBehavior]
		public int WriteLoginLog(Log log)
		{
			return SqlHelper.getInstance.ExcuteInsert<Log>(log, "Log");
		}

		[MOperationBehavior]
		public string GetRejectOrderID(string userID)
		{
			string Sql = string.Format("select RecordID from MoneyOutInfo where UserID='{0}' and Status=2 and DealTime between '{1}' and '{2}'",
			   userID, DateTime.Now.AddSeconds(-40).ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
			object obj = SqlHelper.getInstance.ExcuteScalar(Sql);
			if (obj != null && obj.ToString().Trim() != string.Empty)
			{
				return obj.ToString();
			}
			else
			{
				return string.Empty;
			}
		}

		[MOperationBehavior]
		public string GetVersion()
		{
			return "1.00";
			//return SqlHelper.getInstance.ExcuteScalar("select Version from PlatformVersion").ToString();
		}

		[MOperationBehavior]
		public string Test()
		{
			return "LSYUAN";
		}
	}
}
